<?php

require_once __DIR__ . '/../../vendor/autoload.php';

use JLPay\Core\OrgConfig;
use JLPay\Core\DemoConfig;
use JLPay\Services\Cashier\CashierService;
use JLPay\Models\Cashier\TradeRefundRequest;
use JLPay\Utils\Logger;
use JLPay\Utils\DemoRequestHandler;

/**
 * 收银台 - 交易退款功能使用示例
 */

// =================== 工具函数 =====================
/**
 * 创建配置对象
 */
function createConfig(): OrgConfig
{
    return DemoConfig::createConfig();
}

// =================== 数据构建函数 =====================
/**
 * 构建交易退款请求
 */
function buildTradeRefundRequest(): TradeRefundRequest
{
    $request = new TradeRefundRequest();
    
    // 设置请求参数
    $request->setMerchNo("849584358120018")
        ->setOutTradeNo("ld201911023465531")
        ->setOriOutTradeNo("ld201911023465529")
        ->setTotalAmount("1")
        ->setRemark("退款交易");
    
    return $request;
}

// =================== 示例函数 =====================
/**
 * 交易退款示例
 */
function tradeRefundDemo(): void
{
    $logger = Logger::getInstance();
    $logger->info("开始执行交易退款示例");
    
    // 创建配置对象和收银台服务
    $config = createConfig();
    $cashierService = new CashierService($config);
    
    // 创建交易退款请求
    $request = buildTradeRefundRequest();
    
    // 发送请求 - 使用DemoRequestHandler
    $response = DemoRequestHandler::sendRequestAndHandleResponse(
        $cashierService, 
        $request, 
        "交易退款",
        function($service, $request) {
            return $service->refundTrade($request);
        }
    );

    // 处理响应结果
    if ($response && $response->isSuccess()) {
        $logger->info("响应报文：" . json_encode($response->toArray(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
}

// =================== 主程序 =====================
if (php_sapi_name() === 'cli') {
    $logger = Logger::getInstance();
    
    // 设置日志级别为INFO
    $logger->setLevel('INFO');
    
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 交易退款示例 开始 =====");
    $logger->info(str_repeat("=", 50));
    tradeRefundDemo();
    $logger->info(str_repeat("=", 50));
    $logger->info("===== 交易退款示例执行完毕 =====");
    $logger->info(str_repeat("=", 50));
} 